package com.example.fw;

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.example.tests.GroupData;
import com.example.utils.SortedListOf;

public class GroupHelper extends MainHelper{

	public GroupHelper(ApplicationManager appManager) {
		super(appManager);
	}
	
//------------------ High level methods-------------------------------------------------
	public SortedListOf<GroupData> cachedGroups;
	
	public SortedListOf<GroupData> getGroups() {		
		if (cachedGroups == null) {
			rebuildCachedGroups();			
		}
		return cachedGroups;
	}
	
	public void rebuildCachedGroups() {
			SortedListOf<GroupData> cachedGroups = new SortedListOf<GroupData>();
			appManager.getNaviHelper().openGroupsPage();
			List<WebElement> checkboxes = driver.findElements(By.name("selected[]"));
			for (WebElement checkbox : checkboxes) {
				String title = checkbox.getAttribute("title");					
				String name = title.substring("Select (".length(), title.length() - ")".length());
				cachedGroups.add(new GroupData().withName(name));
			}	
	}

	public GroupHelper createGroup(GroupData groupInput) {
		appManager.getNaviHelper().openGroupsPage();
		clickOnNewGroupButton();
		fillGroupFormInfo(groupInput);
		appManager.getNaviHelper().submitNewCreation();	
		appManager.getNaviHelper().openGroupsPage();
		rebuildCachedGroups();
		return this;
	}		
	
	public GroupHelper deleteGroup(int index) {
		appManager.getNaviHelper().openGroupsPage();
		selectGroupByIndex(index);
		submitGroupDeletion();
		appManager.getNaviHelper().openGroupsPage();
		rebuildCachedGroups();
		cachedGroups = null;
		return this;
	}

	public GroupHelper modifyGroup(int index, GroupData groupInput) {
		appManager.getNaviHelper().openGroupsPage();
		initGroupModification(index);
		fillGroupFormInfo(groupInput);
		submitGroupModification();
		appManager.getNaviHelper().openGroupsPage();
		rebuildCachedGroups();	
		return this;
	}
	
	public GroupHelper fillGroupFormInfo(GroupData groupInput) {
		type(By.name("group_name"), groupInput.getGroup_name());
		type(By.name("group_header"), groupInput.getGroup_header());
		type(By.name("group_footer"), groupInput.getGroup_footer());
		return this;
	}

	
//------------------ Low level methods-------------------------------------------------

	public void submitGroupDeletion() {
		click(By.name("delete"));
	}
	
	public GroupHelper clickOnNewGroupButton() {
		click(By.name("new"));
		return this;
	}

	public GroupHelper initGroupModification(int index) {
		selectGroupByIndex(index);
		click(By.name("edit"));
		return this;
	}

	private void selectGroupByIndex(int index) {
		click(By.xpath("//input[@name='selected[]']["+ (index + 1) + "]"));
	}

	public GroupHelper submitGroupModification() {
		click(By.name("update"));
		cachedGroups = null;
		return this;
	}


}
